<template>
  <page-container title="OTA文件上传" class="container">
    <div class="upload-wrapper">
      <!-- 版本号输入 -->
      <div class="version-input">
        <el-input
          v-model="productType"
          placeholder="请输入产品型号"
          type="text"
          style="margin-top: 10px"
          clearable
        />

        <el-input
          v-model="softwareVersion"
          placeholder="请输入固件版本号（格式：xx.xx.xx）"
          type="text"
          @input="(val) => (softwareVersion = filterVersionInput(val))"
          style="margin-top: 10px"
          clearable
        >
          <template #suffix>
            <span v-if="softwareVersion && !isValidSoftwareVersion">⚠</span>
          </template>
        </el-input>

        <el-input
          v-model="hardwareVersion"
          placeholder="请输入硬件版本号（格式：xx.xx）"
          type="text"
          @input="(val) => (hardwareVersion = filterVersionInput(val))"
          style="margin-top: 10px"
          clearable
        >
          <template #suffix>
            <span
              v-if="hardwareVersion && !isValidHardwareVersion"
              class="error-icon"
              >⚠</span
            >
          </template>
        </el-input>
      </div>

      <!-- 上传组件 -->
      <div class="upload">
        <el-upload
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :show-file-list="false"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽固件包至此或<em>点击选择文件</em>
            <div class="el-upload__tip">最大支持500MB</div>
            <div v-if="selectedFileName" class="file-name">
              <el-icon><document /></el-icon>
              {{ selectedFileName }}
            </div>
          </div>
        </el-upload>

        <!-- 上传按钮 -->
        <el-button
          type="primary"
          :disabled="
            !selectedFile ||
            !productType ||
            !softwareVersion ||
            !hardwareVersion ||
            !isValidSoftwareVersion ||
            !isValidHardwareVersion ||
            isProcessing
          "
          :loading="isProcessing"
          @click="handleUpload"
          class="upload-button"
        >
          开始上传
        </el-button>

        <!--进度条-->
        <el-card v-if="isProcessing" class="progress-card">
          <el-progress
            :percentage="progress"
            :status="progress === 100 ? 'success' : undefined"
            :stroke-width="15"
          />
        </el-card>
      </div>
    </div>
  </page-container>
</template>

<script setup>
import { ref, computed, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, UploadFilled } from '@element-plus/icons-vue'
import { OTAupload, getProgress } from '@/api/clothrequest'

// 响应式数据
const productType = ref(null)
const softwareVersion = ref(null)
const hardwareVersion = ref(null)
const selectedFile = ref(null)
const selectedFileName = ref('')
const isProcessing = ref(false)
const progress = ref(0)
const simulateProgressTimer = ref(null)
const taskId = ref(null)
const progressPollingTimer = ref(null)

// onBeforeUnmount(() => {
//   if (simulateProgressTimer.value) {
//     clearInterval(simulateProgressTimer.value)
//   }
// })

// 修改onBeforeUnmount
onBeforeUnmount(() => {
  ;[simulateProgressTimer, progressPollingTimer].forEach((timer) => {
    if (timer.value) clearInterval(timer.value)
  })
})

const isValidSoftwareVersion = computed(() => {
  return /^\d+\.\d+\.\d+$/.test(softwareVersion.value)
})

const isValidHardwareVersion = computed(() => {
  return /^\d+\.\d+$/.test(hardwareVersion.value)
})

const handleFileChange = (file) => {
  if (!validateFile(file)) return false

  // 新文件覆盖旧文件（单文件模式）
  selectedFile.value = file.raw
  selectedFileName.value = file.name
  return true
}

// 文件验证
const validateFile = (file) => {
  const isSizeValid = file.size <= 500 * 1024 * 1024 // 500MB

  if (!isSizeValid) {
    ElMessage.error('文件大小超过限制（500MB）')
    return false
  }
  return true
}

//执行上传
// const handleUpload = async () => {
//   if (isProcessing.value) return
//   if (!softwareVersion.value || !selectedFile.value) {
//     ElMessage.warning('请选择文件并输入版本号');
//     return;
//   }
//
//   try {
//     isProcessing.value = true
//     progress.value = 0
//     simulateProgress()
//
//     const formData = new FormData();
//
//     formData.append('file', selectedFile.value)
//     formData.append('productType', productType.value);
//     formData.append('softwareVersion', softwareVersion.value);
//     formData.append('hardwareVersion', hardwareVersion.value || '');
//
//     // for (const pair of formData.entries()) {
//     //   console.log(pair[0], pair[1]);
//     // }
//
//     const { data } = await OTAupload(formData);
//     clearInterval(simulateProgressTimer.value)
//
//     if (data.code === 1) {
//       ElMessage.success('上传成功');
//       setTimeout(() => (isProcessing.value = false), 800)
//       selectedFileName.value = ''
//       // 清空状态
//       productType.value = '';
//       softwareVersion.value = '';
//       hardwareVersion.value = '';
//       selectedFile.value = null;
//     } else {
//       ElMessage.error('上传失败：' + (data.message || '未知错误'));
//     }
//   } catch (error) {
//     ElMessage.error(`上传失败：${error.message || '网络错误'}`);
//   } finally {
//     if (progress.value !== 100) {
//       clearInterval(simulateProgressTimer.value)
//       progress.value = 0
//       isProcessing.value = false
//     }
//   }
// }

// 修改后的上传处理函数
const handleUpload = async () => {
  if (isProcessing.value) return
  if (!softwareVersion.value || !selectedFile.value) {
    ElMessage.warning('请选择文件并输入版本号')
    return
  }
  try {
    isProcessing.value = true
    progress.value = 0

    const formData = createFormData()
    const uploadRes = await OTAupload(formData)

    if (uploadRes.data.code === 0) {
      throw new Error(uploadRes.data.data || '网络错误')
    }
    if (uploadRes.data.code !== 1) {
      throw new Error(uploadRes.data.message || '上传失败')
    }

    taskId.value = uploadRes.data.data
    startProgressPolling() // 开始轮询进度
  } catch (error) {
    handleUploadError(error)
  }
}
const handleUploadError = (error) => {
  // 清除所有定时器
  clearInterval(simulateProgressTimer.value)
  clearInterval(progressPollingTimer.value)

  // 重置状态
  progress.value = 0
  isProcessing.value = false

  // 显示错误提示
  ElMessage.error(`上传失败：${error.message}`)

  // 开发环境打印日志
  if (import.meta.env.DEV) {
    console.error('上传错误详情:', error)
  }
}

// 新增方法：启动进度轮询
const startProgressPolling = () => {
  let retryCount = 0
  const MAX_RETRY = 30
  clearInterval(progressPollingTimer.value)

  progressPollingTimer.value = setInterval(async () => {
    try {
      if (retryCount++ > MAX_RETRY) {
        throw new Error('处理超时，请稍后查看状态')
      }
      const progressRes = await getProgress(taskId.value)
      if (progressRes.data.code === 1) {
        const currentProgress = parseFloat(progressRes.data.data)
        if (currentProgress === -1) {
          handleUploadSuccess()
        } else {
          progress.value = Math.min(currentProgress, 99.9) // 防止显示100%
        }
      }
      else {
        throw new Error('进度查询失败')
      }
    } catch (error) {
      console.error('进度获取失败:', error)
    }
  }, 2000) // 每2秒轮询一次
}

// 新增方法：处理上传成功
const handleUploadSuccess = () => {
  clearInterval(progressPollingTimer.value)
  progress.value = 100
  ElMessage.success('上传并处理完成')
  resetStates()
}

// 修改后的重置状态方法
const resetStates = () => {
  setTimeout(() => {
    isProcessing.value = false
    taskId.value = null
    selectedFileName.value = ''
    productType.value = ''
    softwareVersion.value = ''
    hardwareVersion.value = ''
    selectedFile.value = null
  }, 1500)
}

// 新增方法：创建FormData
const createFormData = () => {
  const formData = new FormData()
  formData.append('file', selectedFile.value)
  formData.append('productType', productType.value)
  formData.append('softwareVersion', softwareVersion.value)
  formData.append('hardwareVersion', hardwareVersion.value || '')
  return formData
}

const filterVersionInput = (value) => {
  return value
    .replace(/[^\d.]/g, '') // 移除非数字和点号
    .replace(/\.{2,}/g, '.') // 禁止连续点号
}
</script>

<style lang="scss" scoped>
.container {
  border-radius: 20px;
  font-weight: bold;
  font-size: 17px;
  min-height: 80vh; /* 确保容器有足够高度 */
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.upload-wrapper {
  flex: 1; /* 撑满剩余空间 */
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
  align-items: center; /* 水平居中 */
  width: 100%;
  padding: 30px;
  box-sizing: border-box;

  .version-input {
    width: 100%;
    max-width: 500px;
    margin-bottom: 25px;

    :deep(.el-input) {
      .el-input__wrapper {
        height: 48px;
        border-radius: 8px;
        font-size: 16px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        &::placeholder {
          color: #999;
        }
      }
    }
  }
}

.upload {
  width: 100%;
  max-width: 600px;
  text-align: center;

  .upload-button {
    margin-top: 25px;
    width: 200px;
    height: 48px;
    font-size: 16px;
    border-radius: 8px;
    transition: all 0.3s;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
    }
  }
}

/* 优化上传拖拽区 */
:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  padding: 50px 20px;
  background-color: #f8faff;
  border: 2px dashed #c0c4cc;
  border-radius: 12px;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
    background-color: rgba(64, 158, 255, 0.05);
    transform: translateY(-3px);
  }

  .el-icon--upload {
    font-size: 64px;
    color: #909399;
    margin-bottom: 20px;
  }

  .el-upload__text {
    font-size: 16px;
    color: #606266;
    line-height: 1.5;

    em {
      color: #409eff;
      font-style: normal;
      font-weight: 500;
    }
  }
}

/* 响应式优化 */
@media (max-width: 768px) {
  .container {
    min-height: 70vh;
    border-radius: 16px;
  }

  .upload-wrapper {
    padding: 20px;

    .version-input {
      margin-bottom: 20px;

      :deep(.el-input__wrapper) {
        height: 44px;
        font-size: 15px;
      }
    }
  }

  :deep(.el-upload-dragger) {
    padding: 30px 15px;

    .el-icon--upload {
      font-size: 48px;
    }

    .el-upload__text {
      font-size: 14px;
    }
  }

  .upload .upload-button {
    width: 160px;
    height: 44px;
    font-size: 15px;
  }
}

@media (max-width: 480px) {
  :deep(.el-upload-dragger) {
    padding: 20px 10px;

    .el-icon--upload {
      font-size: 40px;
      margin-bottom: 15px;
    }
  }

  .upload .upload-button {
    width: 100%;
    max-width: 160px;
  }
}
</style>
